from mylearn.models import *
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from mylearn.mylearnser import MylearnGoodsser,MylearnUserser,MylearnIndentser
import time


class LoginView(APIView):
    def get(self, request):
        username = request.GET.get('username')
        phone = request.GET.get('phone')
        user = MylearnUser.objects.filter(username=username, phone=phone).first()
        if user:
            return Response({'code': 200, 'msg': '登录成功', 'username': user.username, 'uid': user.id})
        else:
            return Response({'msg': '账号或密码错误'})


# 展示所有商品
class GoodListView(APIView):
    def get(self, request):
        # 获取当前页，默认第一页
        page = request.GET.get('page', 1)
        # 一夜显示多少个数
        size = request.GET.get('size', 1)
        # 计算从哪开始切
        data_start = (int(page) - 1) * int(size)
        # 计算切到那儿
        data_end = int(page) * int(size)
        # 查询 切片操作
        goods = MylearnGoods.objects.all()[data_start:data_end]
        # 查询所有商品个数
        count = MylearnGoods.objects.count()
        # 序列
        goods_ser = MylearnGoodsser(goods, many=True)
        return Response({"code": 200, "message": goods_ser.data, 'count': count})


#订单提交
class SubmitView(APIView):
    def post(self,request):
        data=request.data
        ser=MylearnIndentser(data=data)
        if ser.is_valid():
            ser.save()
        return Response({'订单提交成功'})

    def get(self,request):
        uid=request.GET.get('uid')
        print(uid)
        order=MylearnIndent.objects.filter(uid=uid)
        print(order)
        orderser=MylearnIndentser(order,many=True)
        return Response({'message':orderser.data})
